package com.synnex.wms.controller;
/**
 * 家属前后台交互
 * 
 * */
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.synnex.wms.pojo.Jiashu;
import com.synnex.wms.service.JiashuService;
import com.synnex.wms.util.PageUtil;

/**
 * JiashuController
 * */

@Controller
@RequestMapping(value = "/Jiashu")
public class JiashuController {

	//日期
	SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	Date currentTime = new Date();
	String csrq = formatter.format(currentTime);
	@Autowired
	private JiashuService JiashuService;
	
	
	 /*分页查询、模糊查询*/
	 @RequestMapping(value = "/page")
	 public void page(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		int pageIndex = 1;//设置初始的当前页，页面显示的都是第一页
        int pageSize = 4;//设置每一页显示几条数据,用于计算总页数，此处设置的值必须与sql语句的limit最后的数值一样
        PageUtil<Jiashu> pageUtil = new PageUtil<Jiashu>();//初始化工具类
        List<Jiashu> list = new ArrayList<Jiashu>();
        if (request.getParameter("pageIndex") != null) {
            pageIndex = Integer.parseInt(request.getParameter("pageIndex"));
        }//对页面上的分页标签传的值,进行获取,也是就点击'上一页或者下一页'传过来的pageindex
        pageUtil.setPageIndex(pageIndex);//保存至工具类
        
        String name = request.getParameter("name");
        String realname = request.getParameter("realname");
        String phone = request.getParameter("phone");
        Jiashu Jiashu = new Jiashu();
        Jiashu.setName(name);
        Jiashu.setRealname(realname);
        Jiashu.setPhone(phone);
        
        int number = JiashuService.pagecount(Jiashu);//调用service层方法计算出总数据量，就是多少条数据.
        pageUtil.setPageNumber(number);//保存至工具类
        pageUtil.setPageSize(pageSize);//保存至工具类
        pageUtil.setPageCount((int) Math.ceil((double) (pageUtil
                .getPageNumber() / pageUtil.getPageSize())) + 1);//计算出总页数,并封装到工具类
        int index = (pageIndex - 1) * pageSize;//计算出每一页从数据库中第几条数据开始取值，也就是limit后面的第一个数字
        Jiashu.setFenye(index);
        list = JiashuService.showlist(Jiashu);//调用service层的方法，取得数据库中的值
        pageUtil.setList(list);//保存到工具类中的集合
        request.setAttribute("pageUtil", pageUtil);//传递到页面，存入值栈中
		request.getRequestDispatcher("/jsp/Jiashu/list.jsp").forward(request,
				response);
	}
	 
	 
	
	/*删除数据*/
	@RequestMapping(value = "/delete/{id}")
	public String delete(@PathVariable Integer id) {
		JiashuService.deleteByPrimaryKey(id);
		return "redirect:/Jiashu/page";
	
	}
	
	/*添加、插入数据*/
	@RequestMapping(value = "/insert")
	public String insertTp(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Jiashu Jiashu=new Jiashu();
	   	 FileItemFactory itemFactory=new DiskFileItemFactory();
	   	 ServletFileUpload fileUpload=new ServletFileUpload(itemFactory);
	   	 try {
				List<FileItem> items=fileUpload.parseRequest(request);
				for(FileItem fileItem:items){
					//判断是否是普通表单数据
					if(fileItem.isFormField()){//是普通表单
						//获取表单名称
						if("name".equals(fileItem.getFieldName())){
							Jiashu.setName(fileItem.getString("utf-8"));
						}else if("password".equals(fileItem.getFieldName())){
							Jiashu.setPassword(fileItem.getString("utf-8"));
						}else if("realname".equals(fileItem.getFieldName())){
							Jiashu.setRealname(fileItem.getString("utf-8"));
						}else if("phone".equals(fileItem.getFieldName())){
							Jiashu.setPhone(fileItem.getString("utf-8"));
						}else if("address".equals(fileItem.getFieldName())){
							Jiashu.setAddress(fileItem.getString("utf-8"));
						}else if("introduce".equals(fileItem.getFieldName())){
							Jiashu.setIntroduce(fileItem.getString("utf-8"));
						}else if("age".equals(fileItem.getFieldName())){
							if(fileItem.getString("utf-8")!=null&&!"".endsWith(fileItem.getString("utf-8"))){
								Jiashu.setAge(Integer.parseInt(fileItem.getString("utf-8")));
							}
						}else if("sex".equals(fileItem.getFieldName())){
							Jiashu.setSex(fileItem.getString("utf-8"));
						}else if("zt".equals(fileItem.getFieldName())){
							if(fileItem.getString("utf-8")!=null&&!"".endsWith(fileItem.getString("utf-8"))){
								Jiashu.setZt(Integer.parseInt(fileItem.getString("utf-8")));
							}
						}
					}else{//文件
						if("picture".equals(fileItem.getFieldName())){
							//获取上传的文件类型
							fileItem.getContentType();
							//获取上传的文件的大小
							fileItem.getSize();
							
							//获取文件名称
							String oldName=fileItem.getName();
							if(!"".equals(oldName)&&oldName!=null){
								//获取文件的后缀
								String type=oldName.substring(oldName.lastIndexOf("."));
								//创建新名称
								String newName=System.currentTimeMillis()+type;
								Jiashu.setPicture(newName);

								
								//上传的路径
								String uploadPath=request.getRealPath("/upload");
								System.out.println("uploadPath:"+uploadPath);
								File parentFile=new File(uploadPath);
								//判断文件是否存在
								if(!parentFile.exists()){
									parentFile.mkdirs();
								}
								File file=new File(parentFile, newName);
								//上传文件
								fileItem.write(file);
							}else{
								//查询原来的图片名称及路径
								
							}
							
						}
					}
				}
						
				int num=JiashuService.insert(Jiashu);
				if(num>0){
					request.getRequestDispatcher("/jsp/login.jsp").forward(request,
							response);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
	   	 	return null;
	}
	
	/*添加、插入数据*/
	@RequestMapping(value = "/update")
	public String update(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Jiashu Jiashu=new Jiashu();
		FileItemFactory itemFactory=new DiskFileItemFactory();
		ServletFileUpload fileUpload=new ServletFileUpload(itemFactory);
		try {
			List<FileItem> items=fileUpload.parseRequest(request);
			for(FileItem fileItem:items){
				//判断是否是普通表单数据
				if(fileItem.isFormField()){//是普通表单
					//获取表单名称
					if("name".equals(fileItem.getFieldName())){
						Jiashu.setName(fileItem.getString("utf-8"));
					}else if("password".equals(fileItem.getFieldName())){
						Jiashu.setPassword(fileItem.getString("utf-8"));
					}else if("realname".equals(fileItem.getFieldName())){
						Jiashu.setRealname(fileItem.getString("utf-8"));
					}else if("phone".equals(fileItem.getFieldName())){
						Jiashu.setPhone(fileItem.getString("utf-8"));
					}else if("address".equals(fileItem.getFieldName())){
						Jiashu.setAddress(fileItem.getString("utf-8"));
					}else if("introduce".equals(fileItem.getFieldName())){
						Jiashu.setIntroduce(fileItem.getString("utf-8"));
					}else if("age".equals(fileItem.getFieldName())){
						if(fileItem.getString("utf-8")!=null&&!"".endsWith(fileItem.getString("utf-8"))){
							Jiashu.setAge(Integer.parseInt(fileItem.getString("utf-8")));
						}
					}else if("sex".equals(fileItem.getFieldName())){
						Jiashu.setSex(fileItem.getString("utf-8"));
					}else if("zt".equals(fileItem.getFieldName())){
						if(fileItem.getString("utf-8")!=null&&!"".endsWith(fileItem.getString("utf-8"))){
							Jiashu.setZt(Integer.parseInt(fileItem.getString("utf-8")));
						}
					}else if("id".equals(fileItem.getFieldName())){
						if(fileItem.getString("utf-8")!=null&&!"".endsWith(fileItem.getString("utf-8"))){
							Jiashu.setId(Integer.parseInt(fileItem.getString("utf-8")));
						}
					}
				}else{//文件
					if("picture".equals(fileItem.getFieldName())){
						//获取上传的文件类型
						fileItem.getContentType();
						//获取上传的文件的大小
						fileItem.getSize();
						
						//获取文件名称
						String oldName=fileItem.getName();
						if(!"".equals(oldName)&&oldName!=null){
							//获取文件的后缀
							String type=oldName.substring(oldName.lastIndexOf("."));
							//创建新名称
							String newName=System.currentTimeMillis()+type;
							Jiashu.setPicture(newName);
							
							
							//上传的路径
							String uploadPath=request.getRealPath("/upload");
							System.out.println("uploadPath:"+uploadPath);
							File parentFile=new File(uploadPath);
							//判断文件是否存在
							if(!parentFile.exists()){
								parentFile.mkdirs();
							}
							File file=new File(parentFile, newName);
							//上传文件
							fileItem.write(file);
						}else{
							//查询原来的图片名称及路径
							
						}
						
					}
				}
			}
			
			int num=JiashuService.updateByPrimaryKey(Jiashu);
			if(num>0){
				
				return "redirect:/Jiashu/select/"+Jiashu.getId();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	
	/*修改数据前，根据id查询数据*/
	@RequestMapping("/toUpdateLocPage/{id}")
	public void toUpdateLocPage(@PathVariable("id") Integer id,
			HttpServletResponse response, HttpServletRequest request)
			throws ServletException, IOException {
		
		Jiashu Jiashu = JiashuService.selectByPrimaryKey(id);
		request.setAttribute("Jiashu", Jiashu);
		request.getRequestDispatcher("/jsp/Jiashu/update.jsp").forward(request,
				response);

	}
	
	
	@RequestMapping("/select/{id}")
	public void select(@PathVariable("id") Integer id,
			HttpServletResponse response, HttpServletRequest request)
			throws ServletException, IOException {
		
		Jiashu Jiashu = JiashuService.selectByPrimaryKey(id);
		request.setAttribute("Jiashu", Jiashu);
		request.getRequestDispatcher("/jsp/Jiashu/list1.jsp").forward(request,
				response);

	}
	
}